<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>AI智能问答</title>
    <link href="/prism/prism.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/7.0.1/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            -webkit-tap-highlight-color: transparent;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #333;
            height: 100vh;
            overflow: hidden;
        }

        .app-container {
            display: flex;
            flex-direction: column;
            height: 100vh;
            max-width: 100%;
        }

        /* Header Styles */
        .header {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
            padding: 15px 20px;
            display: flex;
            align-items: center;
            z-index: 100;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .logo-icon {
            width: 36px;
            height: 36px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 18px;
        }

        .logo-text {
            font-size: 20px;
            font-weight: 700;
            background: linear-gradient(135deg, #667eea, #764ba2);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        /* Chat Container */
        .chat-container {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            display: flex;
            flex-direction: column;
            gap: 15px;
            scroll-behavior: smooth;
        }

        /* Message Styles */
        .message {
            max-width: 85%;
            padding: 15px;
            border-radius: 18px;
            line-height: 1.5;
            position: relative;
            animation: fadeIn 0.3s ease-out;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
            display: flex;
            gap: 10px;
        }

        .message-icon {
            font-size: 20px;
            align-self: flex-start;
        }

        .user-message .message-icon {
            color: rgba(255, 255, 255, 0.9);
        }

        .ai-message .message-icon {
            color: #667eea;
        }

        .message-content {
            flex: 1;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .user-message {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            align-self: flex-end;
            border-bottom-right-radius: 5px;
        }

        .ai-message {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            align-self: flex-start;
            border-bottom-left-radius: 5px;
        }

        /* Message Content Styles */
        .message h1, .message h2, .message h3, .message h4, .message h5, .message h6 {
            margin: 12px 0 8px 0;
            font-weight: 600;
            line-height: 1.4;
        }

        .message h1 {
            font-size: 1.6em;
            border-bottom: 1px solid #eee;
            padding-bottom: 0.3em;
        }

        .message h2 {
            font-size: 1.5em;
            border-bottom: 1px solid #eee;
            padding-bottom: 0.3em;
        }

        .message h3 {
            font-size: 1.4em;
        }

        .message h4 {
            font-size: 1.3em;
        }

        .message h5 {
            font-size: 1.2em;
        }

        .message h6 {
            font-size: 1.1em;
            color: #666;
        }

        .message p {
            margin: 8px 0;
            line-height: 1.6;
        }

        .message ul, .message ol {
            padding-left: 24px;
            margin: 12px 0;
        }

        .message ul {
            list-style-type: disc;
        }

        .message ol {
            list-style-type: decimal;
        }

        .message li {
            margin: 6px 0;
            line-height: 1.5;
        }

        .message pre {
            margin: 15px 0;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        .message code {
            font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Fira Mono', monospace;
            font-size: 0.9em;
            background-color: #f6f8fa;
            padding: 0.2em 0.4em;
            border-radius: 6px;
        }

        .message pre code {
            background: none;
            padding: 0;
        }

        .message blockquote {
            border-left: 4px solid #667eea;
            padding: 0 16px;
            margin: 12px 0;
            color: #666;
        }

        .message strong, .message b {
            font-weight: 600;
        }

        .message em, .message i {
            font-style: italic;
        }

        .message hr {
            border: none;
            border-top: 1px solid #eee;
            margin: 20px 0;
        }

        .message a {
            color: #667eea;
            text-decoration: none;
        }

        .message a:hover {
            text-decoration: underline;
        }

        .message table {
            width: 100%;
            border-collapse: collapse;
            margin: 12px 0;
        }

        .message table th, .message table td {
            padding: 8px 12px;
            border: 1px solid #ddd;
            text-align: left;
        }

        .message table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }

        .message table tr:nth-child(even) {
            background-color: #f8f9fa;
        }

        /* Input Area */
        .input-area {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            padding: 15px 20px;
            box-shadow: 0 -2px 20px rgba(0, 0, 0, 0.1);
        }

        .input-container {
            display: flex;
            gap: 12px;
            align-items: flex-end;
        }

        .message-input {
            flex: 1;
            border: 2px solid #e1e5e9;
            border-radius: 24px;
            padding: 15px 20px;
            font-size: 16px;
            outline: none;
            transition: border-color 0.3s;
            resize: none;
            max-height: 150px;
            background: white;
        }

        .message-input:focus {
            border-color: #667eea;
        }

        .send-button {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea, #764ba2);
            border: none;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .send-button:disabled {
            opacity: 0.6;
            transform: none;
        }

        .send-button:not(:disabled):active {
            transform: scale(0.95);
        }

        .send-button:not(:disabled):hover {
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
        }

        .button-icon {
            font-size: 20px;
        }

        /* Welcome Message */
        .welcome-message {
            text-align: center;
            padding: 30px 20px;
        }

        .welcome-title {
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 15px;
            color: #333;
        }

        .welcome-subtitle {
            font-size: 16px;
            color: #666;
            margin-bottom: 25px;
            line-height: 1.6;
        }

        .features {
            display: flex;
            flex-direction: column;
            gap: 15px;
            margin-top: 20px;
        }

        .feature {
            display: flex;
            align-items: center;
            gap: 12px;
            background: rgba(255, 255, 255, 0.7);
            padding: 15px;
            border-radius: 16px;
            text-align: left;
        }

        .feature-icon {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 18px;
        }

        .typing-indicator {
            display: inline-flex;
            align-items: center;
            padding: 15px;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 18px;
            align-self: flex-start;
            border-bottom-left-radius: 5px;
        }

        .typing-dot {
            width: 8px;
            height: 8px;
            background-color: #667eea;
            border-radius: 50%;
            margin: 0 3px;
            animation: typing 1.4s infinite ease-in-out;
        }

        .typing-dot:nth-child(1) { animation-delay: 0s; }
        .typing-dot:nth-child(2) { animation-delay: 0.2s; }
        .typing-dot:nth-child(3) { animation-delay: 0.4s; }

        @keyframes typing {
            0%, 60%, 100% { transform: translateY(0); }
            30% { transform: translateY(-5px); }
        }

        /* Scrollbar */
        .chat-container::-webkit-scrollbar {
            width: 6px;
        }

        .chat-container::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 3px;
        }

        .chat-container::-webkit-scrollbar-thumb {
            background: rgba(102, 126, 234, 0.3);
            border-radius: 3px;
        }

        .chat-container::-webkit-scrollbar-thumb:hover {
            background: rgba(102, 126, 234, 0.5);
        }

        /* Responsive adjustments */
        @media (min-width: 768px) {
            .message {
                max-width: 75%;
            }
            
            .welcome-title {
                font-size: 28px;
            }
        }
    </style>
</head>
<body>
    <div class="app-container">
        <div class="header">
            <div class="logo">
                <div class="logo-icon">AI</div>
                <div class="logo-text">智能问答</div>
            </div>
        </div>

        <div class="chat-container" id="chat-container">
            <div class="welcome-message">
                <h1 class="welcome-title">你好！我是AI助手</h1>
                <p class="welcome-subtitle">我可以帮助你解答各种问题，提供信息查询和技术支持</p>
                
                <div class="features">
                    <div class="feature">
                        <div class="feature-icon">
                            <i class="fas fa-code"></i>
                        </div>
                        <div>
                            <strong>代码示例</strong>
                            <p>提供多种编程语言的代码示例和解释</p>
                        </div>
                    </div>
                    
                    <div class="feature">
                        <div class="feature-icon">
                            <i class="fas fa-lightbulb"></i>
                        </div>
                        <div>
                            <strong>技术解答</strong>
                            <p>解答各类技术问题和疑难困惑</p>
                        </div>
                    </div>
                    
                    <div class="feature">
                        <div class="feature-icon">
                            <i class="fas fa-graduation-cap"></i>
                        </div>
                        <div>
                            <strong>学习指导</strong>
                            <p>提供学习建议和知识点梳理</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="input-area">
            <div class="input-container">
                <textarea
                        class="message-input"
                        id="question"
                        placeholder="输入你的问题..."
                        rows="1"
                ></textarea>
            <button class="send-button" id="send-button" onclick="sendQuestion()">
                <i class="fas fa-paper-plane button-icon"></i>
            </button>
        </div>
    </div>
    </div>

    <script src="/prism/prism.js"></script>
    <!--    引入marked库用于解析Markdown-->
    <script src="/js/marked.min.js"></script>
    <script>
        // 页面加载完成后初始化marked
        document.addEventListener('DOMContentLoaded', function() {
            initializeMarked();
        });

        function initializeMarked() {
            // 配置marked选项
            marked.setOptions({
                highlight: function (code, lang) {
                    if (Prism.languages[lang]) {
                        try {
                            return Prism.highlight(code, Prism.languages[lang], lang);
                        } catch (e) {
                            console.error('Prism highlight error:', e);
                            return code;
                        }
                    } else {
                        // 如果语言不存在，尝试寻找最接近的语言或者使用纯文本
                        return code;
                    }
                },
                langPrefix: 'language-',
                breaks: true,
                gfm: true,
                headerIds: false,
                mangle: false
            });

            // 设置markdown渲染器以更好地支持各种元素
            const renderer = new marked.Renderer();
            renderer.heading = function (text, level) {
                return `<h${level}>${text}</h${level}>`;
            };

            renderer.code = function (code, language) {
                // 如果没有指定语言，则默认为纯文本
                if (!language || !Prism.languages[language]) {
                    language = 'plaintext';
                }

                // 确保语言存在
                const langClass = `language-${language}`;

                // 高亮代码
                try {
                    const highlighted = Prism.highlight(code, Prism.languages[language], language);
                    // 返回HTML
                    return `<pre class="${langClass}"><code class="${langClass}">${highlighted}</code></pre>`;
                } catch (e) {
                    console.error('Prism highlight error:', e);
                    // 如果高亮失败，返回未高亮的代码
                    return `<pre class="${langClass}"><code class="${langClass}">${code.replace(/&/g, '&amp;').replace(/</g, '&lt;')}</code></pre>`;
                }
            };

            marked.setOptions({renderer});
        }

        // 自动调整文本框高度
        document.getElementById('question').addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight > 150 ? 150 : this.scrollHeight) + 'px';
        });

        async function sendQuestion() {
            const questionInput = document.getElementById('question');
            const question = questionInput.value.trim();
            const sendButton = document.getElementById('send-button');

            if (!question) return;

            // 禁用发送按钮和输入框
            sendButton.disabled = true;
            questionInput.disabled = true;

            // 显示用户消息
            addMessageToChat('user', question);

            // 清空输入框并重置高度
            questionInput.value = '';
            questionInput.style.height = 'auto';

            // 显示正在输入指示器
            const typingIndicator = showTypingIndicator();

            try {
                // 使用流式输出
                const eventSource = new EventSource(`/ai/stream?question=${encodeURIComponent(question)}`);
                let aiMessageElement = null;
                let accumulatedContent = '';

                eventSource.onmessage = function(event) {
                    // 检查是否是结束标记
                    if (event.data.endsWith('[stream ended]')) {
                        eventSource.close();
                        // 启用发送按钮和输入框
                        sendButton.disabled = false;
                        questionInput.disabled = false;
                        questionInput.focus();
                        return;
                    }

                    // 移除正在输入指示器（只在第一次接收消息时）
                    if (typingIndicator.parentNode) {
                        typingIndicator.remove();
                    }

                    // 创建AI消息元素（只在第一次接收消息时）
                    if (!aiMessageElement) {
                        aiMessageElement = createAiMessageElement();
                    }

                    // 累积内容
                    accumulatedContent += event.data;

                    // 更新消息内容
                    updateAiMessageContent(aiMessageElement, accumulatedContent);
                };

                eventSource.onerror = function(event) {
                    eventSource.close();
                    // 启用发送按钮和输入框
                    sendButton.disabled = false;
                    questionInput.disabled = false;
                    questionInput.focus();

                    // 移除正在输入指示器
                    if (typingIndicator.parentNode) {
                        typingIndicator.remove();
                    }

                    // 如果已经有消息在显示，就不添加错误消息了
                    if (!aiMessageElement) {
                        addMessageToChat('ai', '抱歉，连接出现错误');
                    }
                };
            } catch (error) {
                console.error('Error:', error);
                // 移除正在输入指示器
                if (typingIndicator.parentNode) {
                    typingIndicator.remove();
                }
                addMessageToChat('ai', '抱歉，发生错误：' + error.message);
                // 启用发送按钮和输入框
                sendButton.disabled = false;
                questionInput.disabled = false;
                questionInput.focus();
            }
        }

        function createAiMessageElement() {
            const chatContainer = document.getElementById('chat-container');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message ai-message';
            
            // 添加AI图标
            const iconDiv = document.createElement('div');
            iconDiv.className = 'message-icon';
            iconDiv.innerHTML = '<i class="fas fa-robot"></i>';
            messageDiv.appendChild(iconDiv);
            
            // 创建内容容器
            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            messageDiv.appendChild(contentDiv);
            
            chatContainer.appendChild(messageDiv);
            scrollToBottom();
            return contentDiv;
        }

        function updateAiMessageContent(messageElement, content) {
            let parse = marked.parse(content);
            parse = parse.replace(/<code class="([^"]+)">/g, (match, langClass) => {
                // 获取代码块内容
                const code = match.replace(/<\/code>/, '');

                // 高亮代码块
                return `<pre class="${langClass}"><code class="${langClass}">${highlightCode(code, langClass)}</code></pre>`;
            });

            // 处理Markdown内容
            messageElement.innerHTML = parse;

            // 重新高亮代码块



            // 滚动到底部
            scrollToBottom();
        }

        function highlightCode(code, langClass) {
            // 使用highlight.js进行代码高亮
        }

        function addMessageToChat(sender, message) {
            const chatContainer = document.getElementById('chat-container');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${sender}-message`;
            
            // 添加图标
            const iconDiv = document.createElement('div');
            iconDiv.className = 'message-icon';
            if (sender === 'user') {
                iconDiv.innerHTML = '<i class="fas fa-user"></i>';
            } else {
                iconDiv.innerHTML = '<i class="fas fa-robot"></i>';
            }
            messageDiv.appendChild(iconDiv);
            
            // 创建内容容器
            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            
            if (sender === 'ai') {
                // 处理Markdown内容
                contentDiv.innerHTML = marked.parse(message);
            } else {
                // 用户消息直接显示文本
                contentDiv.textContent = message;
            }
            
            messageDiv.appendChild(contentDiv);
            chatContainer.appendChild(messageDiv);

            // 滚动到底部
            scrollToBottom();

            // 重新高亮代码块
            if (typeof Prism !== 'undefined') {
                try {
                    Prism.highlightAll();
                } catch (e) {
                    console.error('Prism highlight error:', e);
                }
            }
        }

        function showTypingIndicator() {
            const chatContainer = document.getElementById('chat-container');
            const typingDiv = document.createElement('div');
            typingDiv.className = 'typing-indicator';
            typingDiv.innerHTML = `
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
                <div class="typing-dot"></div>
            `;
            chatContainer.appendChild(typingDiv);
            scrollToBottom();
            return typingDiv;
        }

        function scrollToBottom() {
            const chatContainer = document.getElementById('chat-container');
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        // 支持回车发送消息（Shift+Enter换行）
        document.getElementById("question").addEventListener("keydown", function(event) {
            if (event.key === "Enter" && !event.shiftKey) {
                event.preventDefault();
                sendQuestion();
            }
        });

        // 初始焦点设置
        window.addEventListener('load', function() {
            document.getElementById('question').focus();
        });
    </script>
</body>
</html>